<template>
  <Modal v-model="showModal" class="coupon-edit-dialog" title="发放优惠券">
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
      <FormItem label="门店" prop="store">
        <CouponStoreSelect v-model="formValidate.store" />
      </FormItem>
      <FormItem label="发放方式">
        <RadioGroup v-model="giftCouponType" vertical @on-change="onGiftCouponTypeChange">
          <Radio v-if="couponDiscountType !== 'CASH_COUPON'" label="BY_QUANTITY" :disabled="!sendByQuantityRight">
            <Input v-model="formValidate.count" :disabled="giftCouponType !== 'BY_QUANTITY'" placeholder="请输入发放数量" type="number" />
          </Radio>
          <Radio label="BINDING_BARCODE" :disabled="!sendByBarcodeRight">
            <Input
              v-model="formValidate.barcode"
              :disabled="giftCouponType !== 'BINDING_BARCODE'"
              type="textarea"
              :autosize="{minRows: 2,maxRows: 5}"
              placeholder="请填写条码,用逗号隔开"
            />
          </Radio>
        </RadioGroup>
      </FormItem>
    </Form>
    <div slot="footer">
      <Button style="margin-left: 8px" @click="onCancel">取消</Button>
      <Button type="primary" :disabled="btnDisabled" @click="onConfirm">确定</Button>
    </div>
  </Modal>
</template>
<script>
import { mapGetters } from 'vuex'
import CouponStoreSelect from '~/CouponStoreSelect'
export default {
  components: {
    CouponStoreSelect
  },
  data () {
    return {
      showModal: false,
      btnDisabled: false,
      formValidate: {
        store: '',
        count: '',
        barcode: ''
      },
      ruleValidate: {
        store: [{ required: true, message: '请选择门店', trigger: 'change' }],
        count: [{ required: true, message: '请填写发放数量', trigger: 'blur' }],
        barcode: [{ required: true, message: '请填写条码', trigger: 'blur' }]
      },
      storeList: [],
      current: 1,
      pages: 0,
      queryStoreName: '',
      selectLoading: false,
      couponId: '',
      giftCouponType: 'BY_QUANTITY',
      sendByQuantityRight: false,
      sendByBarcodeRight: false,
      couponDiscountType: '',
      failedBarcode: []
    }
  },
  computed: {
    ...mapGetters(['userMenu'])
  },
  mounted () {
    this.$bus.$on('showModal', (params) => {
      this.$nextTick(() => {
        this.showModal = true
        this.couponDiscountType = params.type
        this.giftCouponType = params.type === 'CASH_COUPON' ? 'BINDING_BARCODE' : 'BY_QUANTITY' //现金券没有按数量发放
        this.couponId = params.id
        this.$Notice.close('barcodeNotice')
        this.formValidate = {
          store: '',
          count: '',
          barcode: ''
        }
        this.failedBarcode = []
        if (this.$refs.formValidate) this.$refs.formValidate.resetFields()
      })
    })
    // 发放优惠券方式
    this.userMenu.forEach(item => {
      if (item.viewUrl === '/sales/coupon/list/sendByQuantity') {
        this.sendByQuantityRight = item.hasRight
        this.giftCouponType = item.hasRight ? 'BY_QUANTITY' : 'BINDING_BARCODE'
      } else if (item.viewUrl === '/sales/coupon/list/sendByBarcode') {
        this.sendByBarcodeRight = item.hasRight
        this.giftCouponType = item.hasRight ? 'BINDING_BARCODE' : 'BY_QUANTITY'
      }
    })
  },
  methods: {
    onGiftCouponTypeChange (e) {
      this.giftCouponType = e
    },
    onConfirm () {
      if (this.btnDisabled) return
      this.$refs['formValidate'].validate(valid => {
        if (valid) {
          this.btnDisabled = true
          this.handleParam()
        }
      })
    },
    handleParam () {
      let param, url
      if (this.giftCouponType === 'BINDING_BARCODE') {
        this.handleSendCouponByBarcode(url, param)
      } else {
        const reg = /^\d+$/
        if (!reg.test(this.formValidate.count)) {
          this.$Message.error('发放数量应为整数')
          return
        }
        param = {
          couponId: this.couponId,
          giftCouponType: 'BY_QUANTITY',
          storeId: this.formValidate.store,
          quantity: Number(this.formValidate.count)
        }
        url = '/coupon/coupon_receive/gift_coupon_by_quantity'
        this.handleSendCouponByQuantity(url, param)
      }
    },
    handleSendCouponByQuantity (url, param) {
      this.$jsonPost(url, param).then(res => {
        if (res) {
          this.btnDisabled = false
          this.showModal = false
          this.$Message.success('发放成功!')
          this.$emit('complete')
        }
      }).catch((e) => {
        this.btnDisabled = false
        this.showModal = false
      })
    },
    handleSendCouponByBarcode () {
      const barCodeList = this.formValidate.barcode.trim().split(/,|，/).filter(item => item !== '')
      this.loopSendCouponByBarcode(barCodeList, 0)
    },
    async loopSendCouponByBarcode (barCodeList, index) {
      this.barcodeIndex = index
      let barCodeListLength = barCodeList.length
      let params = {
        couponId: this.couponId,
        giftCouponType: 'BINDING_BARCODE',
        storeId: this.formValidate.store,
        barCode: barCodeList[index]
      }
      try {
        await this.sendCouponByBarcode(params)
      } catch (error) {
        this.failedBarcode.push({ barcode: barCodeList[index], reason: error.message || '' })
      } finally {
        if (index < barCodeListLength - 1) {
          this.loopSendCouponByBarcode(barCodeList, index + 1)
        } else {
          this.btnDisabled = false
          this.showModal = false
          if (this.failedBarcode.length) {
            this.$Notice.open({
              name: 'barcodeNotice',
              title: '失败条码: ',
              render: h => {
                return <div>
                  { this.failedBarcode.map(item => {
                    return <div>
                      <span>{item.barcode}: </span>
                      <span>{item.reason}</span>
                    </div>
                  }) }
                </div>
              },
              duration: 0
            })
          } else {
            this.$Message.success('全部发放成功!')
          }
        }
      }
    },
    sendCouponByBarcode (params) {
      return this.$jsonPost('/coupon/coupon_receive/gift_coupon_by_barcode_v2', params)
    },
    onCancel () {
      this.showModal = false
      this.$refs.formValidate.resetFields()
    }
  }
}
</script>
